package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    // 用于匹配URL地址
    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //本次强制类型转换是为了使用子类的特有方法  getRequestURI()
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.定义放行资源
        String[] urls ={
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        //2.获取请求路径
        String requestURI = request.getRequestURI();

        //3.判断是否符合放行条件
        boolean flag = checkUri(urls,requestURI);
            if (flag){
                //请求符合放行条件  直接放行
                filterChain.doFilter(request,response);
                return;
            }

        //4.判断是否登录
        HttpSession session = request.getSession();
        Object employee = session.getAttribute("employee");
            if (employee != null){
                //用户已经登录
                filterChain.doFilter(request,response);
                return;
            }

        //前台用户的登录也需要放行
            Object user = session.getAttribute("user");
            if (user!=null){
                //4. 如果已经登录直接放行
                filterChain.doFilter(request,response);
                return;
            }

        //由于这里不是controller，所以你返回对象的时候需要自己的转换为json，并且写出
        String resultJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(resultJson);

        //5.如果没有登录就返回登录界面

        }



    //检查本次的请求是否符合放行
    private boolean checkUri(String[] urls,String requestURI){
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
